package com.wym.charging.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;

/**
 * @author WangYimin 2024年12月24日 22:40:27
 */
@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI().info(new Info()
                                          .title("Demo API")
                                          .version("1.0")
                                          .description("示例"))
                .components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION,
                                                                new SecurityScheme()
                                                                        .type(SecurityScheme.Type.APIKEY)
                                                                        .scheme("bearer")
                                                                        .bearerFormat("JWT")))
                .addSecurityItem(new SecurityRequirement().addList("BearerAuth"));
    }

    @Bean
    public GlobalOpenApiCustomizer globalOpenApiCustomizer() {
        return openApi -> {
            // 全局添加鉴权参数
            if (openApi.getPaths() != null) {
                openApi.getPaths().forEach((s, pathItem) -> {
                    // 登录接口/验证码不需要添加鉴权参数
                    if (s.equals("/user/register") || s.equals("/user/login")) {
                        return;
                    }
                    // 接口添加鉴权参数
                    pathItem.readOperations().forEach(operation -> operation.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION)));
                });
            }
        };
    }
}
